package com.innovation.chengzhangriji.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.http.AllBabyResponse;
import com.innovation.chengzhangriji.http.Auth;
import com.innovation.chengzhangriji.http.BabyAddRequestBody;
import com.innovation.chengzhangriji.http.BabyAddResponse;
import com.innovation.chengzhangriji.http.BabyResponse;
import com.innovation.chengzhangriji.http.Change;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteButton;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.CuteTwoImageView;
import com.innovation.chengzhangriji.ui.widget.SelectDateLayout;
import com.innovation.chengzhangriji.ui.widget.SelectRoleLayout;
import com.innovation.chengzhangriji.util.FileUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

public class CreateActivity extends BaseLoginActivity implements CuteToolbar.OnClickCuteToolbarListener, View.OnClickListener {

    private static final int BOY = 0;

    private static final int GIRL = 1;

    private static final int UNKNOWN = 2;

    private int mState;

    private int mGender;

    private HeadInfo mHeadInfo;

    private BabyAddRequestBody mBabyBody;

    private BabyResponse mBaby;

    private RoundedImageView mImageHead;

    private SelectRoleLayout mSelectRole;

    private SelectRoleLayout mSelectName;

    private SelectDateLayout mSelectDate;

    private CuteTwoImageView mImageBoy;

    private CuteTwoImageView mImageGirl;

    private CuteTwoImageView mImageUnknown;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String imageUrl = null;
            switch (requestCode) {
                case Config.REQUEST_OPEN_CAMERA:
                    imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                    break;
                case Config.REQUEST_OPEN_PHOTO:
                    imageUrl = data.getStringExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO);
                    break;
            }
            if (!TextUtils.isEmpty(imageUrl)) {
                File imgFile = new File(imageUrl);
                if (imgFile.exists()) {
                    mHeadInfo.setHasHead(true);
                    mHeadInfo.setHeadExtension(FileUtils.getFileExtension(imageUrl));
                    mHeadInfo.setHeadBase64(FileUtils.encodeFileToBase64Binary(imgFile));
                    ImageLoader.getInstance().displayImage("file://" + imageUrl, mImageHead);
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mState = getIntent().getIntExtra(Config.ACTION_EXTERNAL_OPEN_CREATE_STATE, Config.EXTRA_OPEN_CREATE_STATE_READY);
        mHeadInfo = new HeadInfo();
        mBabyBody = new BabyAddRequestBody();
        mBaby = new BabyResponse();
        setupLayout();
    }

    @Override
    protected void onPageStart() {
        MobclickAgent.onPageStart(Config.UMENG_PAGE_CREATE);
    }

    @Override
    protected void onPageEnd() {
        MobclickAgent.onPageEnd(Config.UMENG_PAGE_CREATE);
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {

    }

    @Override
    public void onClick(View v) {
        int gender = -1;
        switch (v.getId()) {
            case R.id.boy:
                gender = BOY;
                break;
            case R.id.girl:
                gender = GIRL;
                break;
            case R.id.unknown:
                gender = UNKNOWN;
                break;
            case R.id.btn_start:
                addBaby();
                break;
            case R.id.image_head:
                openDialog();
                break;
        }
        if (gender != -1) {
            setBabyGender(gender);
        }
    }

    private void setupLayout() {
        setContentView(R.layout.activity_create);
        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);
        mImageHead = (RoundedImageView) findViewById(R.id.image_head);
        CuteTextView textState = (CuteTextView) findViewById(R.id.text_state);
        mSelectName = (SelectRoleLayout) findViewById(R.id.select_name);
        mSelectRole = (SelectRoleLayout) findViewById(R.id.select_role);
        mSelectDate = (SelectDateLayout) findViewById(R.id.select_date);
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
        CuteTextView text = (CuteTextView) findViewById(R.id.select_hint4);
        mImageBoy = (CuteTwoImageView) findViewById(R.id.boy);
        mImageGirl = (CuteTwoImageView) findViewById(R.id.girl);
        mImageUnknown = (CuteTwoImageView) findViewById(R.id.unknown);
        switch (mState) {
            case Config.EXTRA_OPEN_CREATE_STATE_READY:
                textState.setText("备孕中");
                mSelectDate.setCuteHint(R.string.activity_create_role_hint_3_1);
                layout.setVisibility(View.INVISIBLE);
                text.setVisibility(View.INVISIBLE);
                break;
            case Config.EXTRA_OPEN_CREATE_STATE_START:
                textState.setText("怀孕期");
                mSelectDate.setCuteHint(R.string.activity_create_role_hint_3_2);
                break;
            case Config.EXTRA_OPEN_CREATE_STATE_END:
                textState.setText("宝贝出生");
                mSelectDate.setCuteHint(R.string.activity_create_role_hint_3_3);
                mImageUnknown.setVisibility(View.GONE);
                break;
        }

        mImageHead.setOnClickListener(this);
        mImageBoy.setOnClickListener(this);
        mImageGirl.setOnClickListener(this);
        mImageUnknown.setOnClickListener(this);

        mGender = BOY;
        mImageBoy.change();

        CuteButton button = (CuteButton) findViewById(R.id.btn_start);
        button.setOnClickListener(this);
    }

    private void setBabyGender(int gender) {
        if (mGender == gender) {
            return;
        }
        mGender = gender;
        mImageBoy.setInitImage();
        mImageGirl.setInitImage();
        mImageUnknown.setInitImage();
        switch (mGender) {
            case BOY:
                mImageBoy.change();
                break;
            case GIRL:
                mImageGirl.change();
                break;
            case UNKNOWN:
                mImageUnknown.change();
                break;
        }
    }

    private void openDialog() {
        final CharSequence[] items = {"拍照", "从手机相册选择"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加头像");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                switch (item) {
                    case 0:
                        startHeadCameraForResult();
                        break;
                    case 1:
                        startHeadSelectForResult();
                        break;
                }
            }
        });
        builder.create().show();
    }

    private void addBaby() {

        // 判断是否有数据为空
        if (TextUtils.isEmpty(mSelectName.getText()) || TextUtils.isEmpty(mSelectRole.getText())) {
            tipShow("请填写完整的信息");
            return;
        }

        if (mHeadInfo.isHasHead()) {
            babyHeadUpload();
        } else {
            babyUpload();
        }
    }

    private void babyHeadUpload() {
        LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            return;
        }
        String phone = login.getPhone();
        String token = login.getToken().getAccessToken();
        Client.requestPictureResourceUpload(this, phone, token, mHeadInfo.getHeadExtension(), mHeadInfo.getHeadBase64(), new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                dismissProgressDialog();
                mHeadInfo.setHeadServerUrl(get(value.toString(), String.class));
                babyUpload();
            }

            @Override
            public void onChZhRJFailure(String value) {
                tipShow(value);
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                tipShow(value);
                dismissProgressDialog();
                finish();
            }
        }, networkUnavailableSampleImpl());
    }

    private void babyUpload() {
        final LoginInfo login = Config.getLoginInfo(this);
        if (login == null) {
            return;
        }
        final String parentID = login.getUserID();
        final String phone = login.getPhone();
        final String token = login.getToken().getAccessToken();
        setBabyAddRequestBody();
        Client.requestBabyAdd(this, phone, token, getChanges(), new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                BabyAddResponse response = get(value.toString(), BabyAddResponse.class);
                if (response != null) {
                    int id = response.getId();
                    login.setBabyID(id);
                    setLoginInfo(login);
                    // 重新请求所有宝贝信息
                    getAllBabyInfo(login);
                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
                finish();
            }
        }, networkUnavailableSampleImpl());
    }

    private void getAllBabyInfo(final LoginInfo loginInfo) {
        final String id = loginInfo.getUserID();
        final String phone = loginInfo.getPhone();
        final String token = loginInfo.getToken().getAccessToken();
        Client.requestAllBaby(this, phone, token, new ResponseHandler() {

            @Override
            public void onInnovationStart() {
                showProgressDialog(null, null);
            }

            @Override
            public void onInnovationSuccess(JsonElement value) {
                Logger.d("获取所有宝贝信息成功" + value.toString());
                AllBabyResponse response = get(value.toString(), AllBabyResponse.class);
                // 修改为直接进入Timeline
                if (response != null) {
                    setLoginInfo(loginInfo);
                    int length = response.getData().length;
                    int[] childIDArray = new int[length];
                    Auth[] auth = new Auth[length];
                    for (int i = 0; i < length; i++) {
                        childIDArray[i] = response.getData()[i].getId();
                        auth[i] = response.getData()[i].getAuth();
                    }
                    insertOrReplaceInTxBabyAndParent(id, auth, childIDArray);
                    insertOrReplaceInTxBaby(response.getData());
                    startTimelineActivity();
                }
                dismissProgressDialog();
            }

            @Override
            public void onChZhRJFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

            @Override
            public void onChZhRJTokenFailure(String value) {
                dismissProgressDialog();
                tipShow(value);
            }

        }, networkUnavailableSampleImpl());
    }


    private void setBabyAddRequestBody() {
        String name = mSelectName.getText();
        String memberName = mSelectRole.getText();
        mBabyBody.setName(name);
        mBabyBody.setParentName(memberName);
        mBaby.setName(name);
        mBaby.setParentName(memberName);
        switch (mState) {
            case Config.EXTRA_OPEN_CREATE_STATE_READY:
                mBabyBody.setState(Client.STATE_READY);
                mBabyBody.setLastDate(mSelectDate.getTime());
                mBaby.setState(Client.STATE_READY);
                mBaby.setLastDate(mSelectDate.getTime());
                break;
            case Config.EXTRA_OPEN_CREATE_STATE_START:
                mBabyBody.setState(Client.STATE_START);
                mBabyBody.setDueDate(mSelectDate.getTime());
                mBaby.setState(Client.STATE_START);
                mBaby.setDueDate(mSelectDate.getTime());
                break;
            case Config.EXTRA_OPEN_CREATE_STATE_END:
                mBabyBody.setState(Client.STATE_END);
                mBabyBody.setBirthday(mSelectDate.getTime());
                mBaby.setState(Client.STATE_END);
                mBaby.setBirthday(mSelectDate.getTime());
                break;
        }
        switch (mGender) {
            case BOY:
                mBabyBody.setGender(Client.BOY);
                mBaby.setGender(Client.BOY);
                break;
            case GIRL:
                mBabyBody.setGender(Client.GIRL);
                mBaby.setGender(Client.GIRL);
                break;
            case UNKNOWN:
                mBabyBody.setGender(Client.UNKNOWN);
                mBaby.setGender(Client.UNKNOWN);
                break;
        }
        if (mHeadInfo.isHasHead()) {
            mBabyBody.setImageUrl(mHeadInfo.getHeadServerUrl());
            mBaby.setImageUrl(mHeadInfo.getHeadServerUrl());
        }
    }

    private Change[] getChanges() {
        return mBabyBody.getBabyAddRequestBody();
    }

    private void startHeadCameraForResult() {
        Intent intent = new Intent(CreateActivity.this, HeadCameraActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_CAMERA);
    }

    private void startHeadSelectForResult() {
        Intent intent = new Intent(CreateActivity.this, HeadPhotoActivity.class);
        startActivityForResult(intent, Config.REQUEST_OPEN_PHOTO);
    }

    private class HeadInfo {

        private boolean hasHead;

        private String headBase64;

        private String headExtension;

        private String headServerUrl;

        public boolean isHasHead() {
            return hasHead;
        }

        public void setHasHead(boolean hasHead) {
            this.hasHead = hasHead;
        }

        public String getHeadBase64() {
            return headBase64;
        }

        public void setHeadBase64(String headBase64) {
            this.headBase64 = headBase64;
        }

        public String getHeadExtension() {
            return headExtension;
        }

        public void setHeadExtension(String headExtension) {
            this.headExtension = headExtension;
        }

        public String getHeadServerUrl() {
            return headServerUrl;
        }

        public void setHeadServerUrl(String headServerUrl) {
            this.headServerUrl = headServerUrl;
        }
    }
}
